<?php

namespace app\common\model;

use app\common\model\cache\airportCache;
use app\common\util\ErrorCode;
use app\common\util\Tools;
use think\Model;

/**
 * Class Auth
 * @package app\common\model
 * 机场的线路表
 */
class trAirportLine extends Model
{
    use airportCache;
    protected $pk = 'id';
    protected $resultSetType = 'collection'; //申明结果集是数据集对象（collection），查询结果才能用toArray()方法转为数组
    protected $name = "airport_line"; //表名
    public $havingData = []; //存放已经获取的数据，减少数据库查询次数

    protected $type = [
        'create_time'  =>  'timestamp:Y-m-d H:i',
        'update_time'  =>  'timestamp:Y-m-d H:i',
    ];

    public function transferField($data){
        if(!$data){
            return [];
        }
        $data = Tools::transferFields($data);
        if(isset($data[0])){
            if(isset($data[0]["carType"])){
                $carTypeModel = new trCarType();
            }
            if(isset($data[0]["airport"])){
                $airportModel = new trAirport();
            }
            foreach ($data as $k => $item){
                if(isset($item["carType"])){
                    if(empty($havingData["carType"][$item["carType"]])) {
                        $data[$k]["carTypeText"] = $havingData["carType"][$item["carType"]] = $carTypeModel->getValue("name", ["id" => $item["carType"]]);
                    }else{
                        $data[$k]["carTypeText"] = $havingData["carType"][$item["carType"]];
                    }
                }
                if(isset($item["airport"])){
                    if(empty($havingData["airport"][$item["airport"]])) {
                        $data[$k]["airportText"] = $havingData["airport"][$item["airport"]] = $airportModel->getValue("name", ["id" => $item["airport"]]);
                    }else{
                        $data[$k]["airportText"] = $havingData["airport"][$item["airport"]];
                    }
                }
                if(isset($item["type"])){   //类型；1接机，2送机
                    if($item["type"] == "1"){
                        $data[$k]["typeText"] = "接机";
                    }else if($item["type"] == "2"){
                        $data[$k]["typeText"] = "送机";
                    }else{
                        $data[$k]["typeText"] = "其它";
                    }
                }
                if(isset($item["provinceCode"])){
                    $data[$k]["pcaText"] = Tools::getNameByPCA($item["provinceCode"], $item["cityCode"], $item["areaCode"]);
                }
            }
        }else{
            if(isset($data["carType"])){
                $carTypeModel = new trCarType();
                if(empty($havingData["carType"][$data["carType"]])) {
                    $data["carTypeText"] = $havingData["carType"][$data["carType"]] = $carTypeModel->getValue("name", ["id" => $data["carType"]]);
                }else{
                    $data["carTypeText"] = $havingData["carType"][$data["carType"]];
                }
            }
            if(isset($data["airport"])){
                $airportModel = new trAirport();
                if(empty($havingData["airport"][$data["airport"]])) {
                    $data["airportText"] = $havingData["airport"][$data["airport"]] = $airportModel->getValue("name", ["id" => $data["airport"]]);
                }else{
                    $data["airportText"] = $havingData["airport"][$data["airport"]];
                }
            }
            if(isset($data["type"])){   //类型；1接机，2送机
                if($data["type"] == "1"){
                    $data["typeText"] = "接机";
                }else if($data["type"] == "2"){
                    $data["typeText"] = "送机";
                }else{
                    $data["typeText"] = "其它";
                }
            }
            if(isset($data["provinceCode"])){
                $data["pcaText"] = Tools::getNameByPCA($data["provinceCode"], $data["cityCode"], $data["areaCode"]);
            }
        }
        return $data;
    }

    //分页获取所有字段数据
    public function getList($field = '*', $filter = [], $page = 1, $limit = 10, $order = "create_time desc", $paginate = true){
        $db = self::where($filter)->field($field)->order($order);
        if($paginate){
            $data = $db->paginate(array('page' => $page, 'list_rows' => $limit));
            if($data){
                $data = $data->toArray();
                $data["data"] = $this->transferField($data["data"]);
                return $data;
            }
        }else{
            if($page && $limit)
                $db->limit($page-1, $limit);
            $data = $db->select();
            $data = $this->transferField($data->toArray());
            return $data;
        }
        return [];
    }

    //根据条件获取数量
    public function getCount($filter){
        if(!empty($filter)){
            return self::where($filter)->count();
        }else{
            $filter["mall_id"] = request()->mallData["id"];
            return self::where($filter)->count();
        }
    }

    // 操作数据库的数据检查
    public function pre_data_check($data){
        $result = Tools::checkDataBaseFields(self::getTable(), $data);
        if(isset($result["code"])){
            return $result;
        }
        if(isset($data["ride_number"]) && (!is_numeric($data["ride_number"]) || $data["ride_number"] < 0)){
            return ErrorCode::code("params_format", "荷载人数");
        }
        if(isset($data["default_price"]) && (!is_numeric($data["default_price"]) || $data["default_price"] < 0)){
            return ErrorCode::code("params_format", "默认价格");
        }
        if(isset($data["default_commission"]) && (!is_numeric($data["default_commission"]) || $data["default_commission"] < 0)){
            return ErrorCode::code("params_format", "默认佣金");
        }
        if(!empty($data["open_weekend"])){
            if(isset($data["weekend_price"]) && (!is_numeric($data["weekend_price"]) || $data["weekend_price"] < 0)){
                return ErrorCode::code("params_format", "周末价格");
            }
            if(isset($data["weekend_commission"]) && (!is_numeric($data["weekend_commission"]) || $data["weekend_commission"] < 0)){
                return ErrorCode::code("params_format", "周末佣金");
            }
        }
        if(!empty($data["open_date"])){
            if(empty($data["date_between"])){
                return ErrorCode::code("params_not_exist", "车票日期范围");
            }
            if(isset($data["date_price"]) && (!is_numeric($data["date_price"]) || $data["date_price"] < 0)){
                return ErrorCode::code("params_format", "日期价格");
            }
            if(isset($data["date_commission"]) && (!is_numeric($data["date_commission"]) || $data["date_commission"] < 0)){
                return ErrorCode::code("params_format", "日期佣金");
            }
        }
        return true;
    }

    //添加
    public function add($data, $getId=false){
        if(!$data)
            return true;
        $result = $this->pre_data_check($data);
        if(isset($result["code"])){
            return $result;
        }
        $data["mall_id"] = request()->mallData["id"];
//        if($this->getCount([
//            ["airport", '=', $data["airport"]], ["province_code", '=', $data["province_code"]],
//            ["city_code", '=', $data["city_code"]], ["area_code", '=', $data["area_code"]], ["mall_id", '=', $data["mall_id"]]
//        ])){
//            return ErrorCode::code("customized", "线路已添加");
//        }
        if(empty($data["create_time"])) $data["create_time"] = time();
        if(empty($data["update_time"])) $data["update_time"] = time();
        $id = self::insertGetId($data);
        if($id){
            $data = Tools::transferFields($data);
            $this->toSavePCACache($id, $data);
            if(!isset($data["status"]) || $data["status"] == "1") { //开启状态的路线才缓存，用于小程序展示线路选择，缓存用redis的有序列表
                $data["type"] == "1" ? $this->toSaveBasic_1_Cache($id, $data, 1) : $this->toSaveBasic_2_Cache($id, $data, 1);
            }
            return $getId ? $id : true;
        }else{
            return false;
        }
    }

    //更新
    public function doUpdate($data, $filter = []){
        if(!$data)
            return true;
        if(isset($filter[0]))
            return false;
        if(!isset($filter["id"])) {
            $filter["id"] = $this->getValue("id", $filter);
        }
//        if(isset($data["airport"]) && $this->getCount([
//                ["airport", '=', $data["airport"]], ["province_code", '=', $data["province_code"]],
//                ["city_code", '=', $data["city_code"]], ["area_code", '=', $data["area_code"]],
//                ["id", '<>', $filter["id"]], ["mall_id", '=', request()->mallData["id"]]
//            ])){
//            return ErrorCode::code("customized", "线路已添加");
//        }
        $result = $this->pre_data_check($data);
        if(isset($result["code"])){
            return $result;
        }
        if(empty($data["update_time"])) $data["update_time"] = time();
        if(self::save($data, $filter)){
            if(isset($filter["id"])) {
                $data = Tools::transferFields($data);
                $this->toSavePCACache($filter["id"], $data);
                if (!isset($data["type"])) {
                    $data["type"] = $this->getValue("type", ["id" => $filter["id"]]);
                }
                if ($data["type"] == "1") {
                    if (!isset($data["status"]) || $data["status"] == "1") //开启状态的路线才缓存，用于小程序展示线路选择
                        $this->toSaveBasic_1_Cache($filter["id"], $data, 2);
                    else
                        $this->delBasic_1_Cache($filter["id"]);
                } else {
                    if (!isset($data["status"]) || $data["status"] == "1") //开启状态的路线才缓存，用于小程序展示线路选择
                        $this->toSaveBasic_2_Cache($filter["id"], $data, 2);
                    else
                        $this->delBasic_2_Cache($filter["id"]);
                }
            }
            return true;
        }else{
            return false;
        }
    }

    //获取某字段的值
    public function getValue($field, $filter = []){
        if(!is_array($field)){
            return self::where($filter)->value($field);
        }
        return false;
    }

    //获取某字段的所有值
    public function getColumn($field, $filter = [], $key = ''){
        if(!is_array($field)){
            return self::where($filter)->column($field, $key);
        }
        return [];
    }

    //获取多字段数据
    public function getFields($field, $filter = [], $one = true, $toArray = true){ //缓存方法：缓存所有字段，只返回需要的字段
        if($one){
            $data = self::where($filter)->field($field)->find();
            return $data ? ($toArray ? $this->transferField($data->toArray()) : Tools::transferFields($data->getData())) : [];
        }else{
            $data = self::where($filter)->field($field)->select();
            return $data ? ($toArray ? $this->transferField($data->toArray()) : $data) : [];
        }
    }

    //根据ID删除数据
    public function delById($id){
        if(is_array($id)){
            $result = self::where('id', 'in', $id)->delete();
        }else{
            $result = self::where('id', $id)->delete();
            $id = [$id];
        }
        if($result && ($redisObject = redis_object()) !== false){
            foreach ($id as $i){
                $this->delPCACache($i);
                $this->delBasic_1_Cache($i);
                $this->delBasic_2_Cache($i);
            }
        }
        return $result;
    }
}